﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace Common.Tools
{
    public class LogHelper
    {
        protected LogHelper() { }
        private static LogHelper _instance;
        private static readonly object _syncRoot = new object();

        public static LogHelper Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_syncRoot)
                    {
                        //Double-Check双重检查锁定,对于多线程访问时控制
                        if (_instance == null)
                        {
                            _instance = new LogHelper();
                        }
                    }
                }
                return _instance;
            }
        }

        private string GetPath(ErrorLevelEnum errorLevelEnum)
        {
            //var directoryPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "\\Log\\", errorLevelEnum.ToString());
            var directoryPath = AppDomain.CurrentDomain.BaseDirectory + "Log\\" + errorLevelEnum.ToString();
            if (!Directory.Exists(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
            }
            return Path.Combine(directoryPath, string.Format("log_{0:yyyy-MM-dd_HH}.txt", DateTime.Now));
        }

        public void WriteLog(string msg, ErrorLevelEnum errorLevelEnum = ErrorLevelEnum.Info)
        {
            try
            {
                var logTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                StringBuilder logMessage = new StringBuilder();
                logMessage.Append("\r\n");
                logMessage.AppendFormat("******************************[{0}]******************************", logTime);//30-25-30
                logMessage.Append("\r\n");
                logMessage.Append(msg);
                logMessage.Append("\r\n");
                logMessage.Append("******************************[**********End**********]******************************");
                using (var sw = new StreamWriter(GetPath(errorLevelEnum), true))
                {
                    sw.WriteLine(logMessage.ToString());
                }
            }
            catch (Exception ex)
            {

            }
        }
    }

    /// <summary>
    /// 日志信息级别
    /// 日志信息输出的优先级从高到低至少应分为五档，分别是Fatal、ERROR、WARN、INFO、DEBUG。
    /// </summary>
    public enum ErrorLevelEnum
    {
        /// <summary>
        /// 致命
        /// </summary>
        Fatal = 0,
        /// <summary>
        /// 错误
        /// </summary>
        Error,
        /// <summary>
        /// 警告
        /// </summary>
        Warn,
        /// <summary>
        /// 信息
        /// </summary>
        Info,
        /// <summary>
        /// 调试
        /// </summary>
        Debug,
        /// <summary>
        /// 微量
        /// </summary>
        Trace,
    }
}
